<template>
  <div v-show="isShareImg" class="isShareImg">
    <!-- 图片轮播 -->
    <div class="shareImgContainer" @touchmove.prevent>
      <div
        v-if="type == 1"
        v-for="(items, index) in shareData"
        :key="index"
        class="shareCon"
      >
        <div class="shareImgBg" ref="imageTofile">
          <img :src="items.bgUrl" alt="" />

          <div class="linkCodeContent">
            <div class="linkCode">
              <vue-qr
                :correctLevel="2"
                :text="downloadData.url"
                :logoSrc="downloadData.icon"
                :margin="10"
                :logoMargin="5"
                colorDark="#000"
                colorLight="#fff"
                :logoScale="0.4"
                :logoCornerRadius="10"
                :size="400"
              ></vue-qr>
            </div>
            <div class="linkCodeText">
              <div class="linkCodeTitle">{{ dataConfig.periodsName }}</div>
              <div class="linkCodeSubTitle">识别二维码 解锁更多精彩</div>
            </div>
          </div>
        </div>
      </div>
      <div class="swiper-wrap" v-if="type == 2">
        <div
          class="answerShare-swiper-container"
          ref="answerShare-swiper-container"
        >
          <div class="swiper-wrapper">
            <div
              class="swiper-slide"
              v-for="(items, index) in shareData"
              :key="index"
            >
              <div
                class="shareImgBg"
                :id="'imageTofile_' + index"
                :ref="'imageTofile_' + index"
              >
                <div class="answerCard">
                  <img
                    class="recommendBg"
                    :src="dataConfig.recomBackImageUrl"
                    alt=""
                  />
                  <div
                    class="cardContent"
                    :style="[
                      { background: dataConfig.recomFrontColor },
                      { 'border-color': dataConfig.recomFrontEdgeColor },
                    ]"
                  >
                    <div
                      class="cardTop"
                      :style="[
                        {
                          margin:
                            items.mainTitle && items.subtitle
                              ? ''
                              : '.21rem 0 .21rem',
                        },
                      ]"
                    >
                      <div class="cornerLabel">
                        <div
                          v-if="items.mainTitle"
                          :style="[
                            { background: dataConfig.recomMainTitleBackColor },
                            { color: dataConfig.recomMainTitleColor },
                          ]"
                          class="mainTitle"
                        >
                          <span>{{ items.mainTitle }}</span>
                        </div>
                        <div
                          v-if="items.subtitle"
                          :style="[
                            { background: dataConfig.recomSubtitleBackColor },
                            { color: dataConfig.recomSubtitleColor },
                          ]"
                          class="subTitle"
                        >
                          <span>{{ items.subtitle }}</span>
                        </div>
                      </div>
                      <div class="fundManagerInfo">
                        <div class="managerHead" v-if="items.recomImageUrl">
                          <div class="headmg">
                            <img :src="items.recomImageUrl" alt="" />
                          </div>
                        </div>
                        <div class="managerInfo">
                          <div
                            class="marketTalk"
                            :style="{ color: dataConfig.recomMarketTalkColor }"
                          >
                            <p
                              v-for="(item, index) in operationStr(
                                items.marketTalk,
                                items.recomImageUrl
                              )"
                            >
                              {{ item }}
                            </p>
                          </div>
                          <div class="marketLabels">
                            <div
                              :style="[
                                { color: dataConfig.recomLabelColor },
                                {
                                  'border-color':
                                    dataConfig.recomLabelEdgeColor,
                                },
                              ]"
                              class="labelItem"
                              v-for="(element, index) in tips(items.labels)"
                              :key="index"
                            >
                              <span class="labelItemText">{{ element }}</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="cardBottom" v-if="items.fundCode">
                      <div class="cornerLabel2" v-if="items.fundRecomImageUrl">
                        <img :src="items.fundRecomImageUrl" alt="" />
                      </div>
                      <div class="fundInfo">
                        <div class="fundInfoLeft">
                          <div
                            :class="
                              items.revenueValue[0] == '-' ? 'green' : 'red'
                            "
                            class="fundInfoValue"
                          >
                            {{ items.revenueValue || "--" }}
                          </div>
                          <div
                            class="fundInfoName"
                            v-if="items.revenueTypeDesc"
                            :style="{
                              color: dataConfig.recomRevenueLabelColor,
                            }"
                          >
                            {{ items.revenueTypeDesc }}
                          </div>
                        </div>
                        <div class="fundInfoRight">
                          <div
                            class="fundInfoTitle"
                            :style="{ color: dataConfig.recomFundNameColor }"
                          >
                            {{ handleStr(items.fundName, 10) }}
                          </div>
                          <div
                            class="fundInfoSubTitle"
                            :style="{
                              color: dataConfig.recomFundMarketTalkColor,
                            }"
                          >
                            {{ handleStr(items.fundMarketTalk, 12) }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="answerCardLinkCodeContent">
                  <div class="answerCardLinkCode">
                    <vue-qr
                      :correctLevel="2"
                      :text="downloadData.url"
                      :logoSrc="downloadData.icon"
                      :margin="10"
                      :logoMargin="5"
                      colorDark="#000"
                      colorLight="#fff"
                      :logoScale="0.4"
                      :logoCornerRadius="10"
                      :size="400"
                    ></vue-qr>
                  </div>
                  <div class="answerCardLinkCodeText">
                    <div class="answerCardLinkCodeTitle">
                      {{ dataConfig.periodsName }}
                    </div>
                    <div class="answerCardLinkCodeSubTitle">
                      识别二维码 解锁更多精彩
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="swiper-pagination" v-if="shareData.length > 1"></div>
          <!--分页器。如果放置在swiper-container外面，需要自定义样式。-->
        </div>
      </div>
    </div>
    <!-- 微信分享弹框 -->
    <div class="isVisibleShare" @touchmove.prevent v-if="shareData.length > 0">
      <div class="shareContent">
        <div class="shareDetail">
          <div
            class="shareItem"
            v-for="(items, index) in shareOperateArr"
            :key="index"
          >
            <div class="itemCenter" @click="goShare(items.type)">
              <div class="shareItemImg">
                <img :src="items.imgSrc" alt="" />
              </div>
              <div class="shareItemText">{{ items.operateWord }}</div>
            </div>
          </div>
        </div>
        <div class="shareCanel" @click="isShare">取消</div>
      </div>
    </div>
  </div>
</template>
<script>
import vueQr from "vue-qr";
import html2canvas from "html2canvas";
import { mapState } from "vuex";
import "swiper/dist/css/swiper.min.css";
import Swiper from "swiper";
export default {
  props: {
    dataConfig: { type: Object, default: {} },
    shareData: { type: Array, default: [] },
    type: { type: Number },
    isShareImg: { type: Boolean, default: false },
    isGetShare: { type: Boolean, default: false },
    shareTaskId: { type: Number },
    taskComplete: { type: Number },
  },
  components: { vueQr },
  data() {
    return {
      periods: this.$utils.getParams(this, "periods"),
      shareOperateArr: [
        {
          imgSrc: require("@/assets/imgs/weChart.png"),
          operateWord: "微信好友",
          type: "shareFriend",
        },
        {
          imgSrc: require("@/assets/imgs/friend.png"),
          operateWord: "微信朋友圈",
          type: "shareWX",
        },
        {
          imgSrc: require("@/assets/imgs/download.png"),
          operateWord: "保存到相冊",
          type: "save",
        },
      ],
      isShareClick: false, // 分享按钮是否已被点击
      downloadImgErr: false, // 获取图片失败
      loadingImgErr: true, // 加载图片中
      wnningPercentConLeft: "",
      indicator: 0,
      shareSwiper: null,
      downloadData: {
        url:
          this.dataConfig.actName == "lotteryAct"
            ? `${this.$urls.domain}${
                this.$urls.lotteryHomePage_url
              }?periods=${this.$utils.getParams(this, "periods")}&isshare=1`
            : `${this.$urls.domain}${
                this.$urls.answerHomePage_url
              }?periods=${this.$utils.getParams(this, "periods")}&isshare=1`,
        icon: require("@/assets/imgs/logo.png"),
      },
    };
  },
  computed: {
    ...mapState(["isAndroid", "isIOS"]),
  },
  created() {
    let _this = this;
    if (_this.isAndroid && window.jsObj) {
      window.jsObj.jsCallback = (functionName, reqId, data) => {
        if (functionName == "wxShareSave") {
          _this.getShareResult(data);
        }
      };
    } else if (_this.isIOS) {
      window["jsCallback"] = (functionName, reqId, data) => {
        if (functionName == "wxShareSave") {
          _this.getShareResult(data);
        }
      };
    }
  },
  mounted() {
    var that = this;
    that.shareSwiper = new Swiper(".answerShare-swiper-container", {
      slidesPerView: 1.5,
      centeredSlides: true,
      spaceBetween: 10,
      pagination: {
        el: ".swiper-pagination",
      },
      initialSlide: 0,
      observer: true, //修改swiper自己或子元素时，自动初始化swiper
      observeParents: true, //修改swiper的父元素时，自动初始化swiper
      onSlideChangeEnd: function (swiper) {
        swiper.update();
        swiper.startAutoplay();
        swiper.reLoop();
      },
    });
  },
  methods: {
    subSRT(data, count) {
      let arr = [];
      for (let i = 0, len = data.length / count; i < len; i++) {
        let subStr = data.substr(0, count);
        arr.push(subStr);
        data = data.replace(subStr, "");
      }
      return arr;
    },
    operationStr(str, url) {
      if (str) {
        if (url) {
          if (str.length > 60) {
            let arr = this.subSRT(str.substr(0, 59), 12);
            arr[arr.length - 1] = arr[arr.length - 1] + "...";
            return arr;
          } else {
            return this.subSRT(str, 12);
          }
        } else {
          return this.subSRT(str, 19);
        }
      }
    },
    handleStr(str, num) {
      if (str.length - 1 > num) {
        return str.substr(0, num) + "...";
      } else {
        return str.substr(0, num);
      }
    },
    // 转数组
    tips(str) {
      if (str) {
        return str.split("，");
      }
    },
    //分享弹框显示或隐藏
    isShare() {
      this.$emit("shareDialog", this.isShareImg ? false : true);
      this.shareData.length > 1 && this.shareSwiper.slideTo(0);
    },
    //分享
    goShare(type) {
      let _this = this;
      // 自定义埋点
      this.sendSaHtmd(type);
      if (_this.isShareClick) {
        _this.$commonJS.toastI("图片正在生成中，请稍后...");
      } else {
        _this.isShareClick = true;
        let dom =
          _this.type == 1
            ? _this.$refs["imageTofile"][0]
            : _this.$refs[`imageTofile_${_this.shareSwiper.activeIndex}`][0];
        html2canvas(dom, {
          backgroundColor: null,
          useCORS: true, // 解决文件跨域问题
        })
          .then((canvas) => {
            let url = canvas.toDataURL("image/png");
            //传给app端的base64不需要前缀
            url = url.replace(/^data:image\/\w+;base64,/, "");
            if (url) {
              _this.wxShareSend(type, url);
              if (
                (type == "shareFriend" || type == "shareWX") &&
                !this.isGetShare &&
                this.taskComplete == 0
              ) {
                // 判断是否做完任务
                this.$parent.finishTask(
                  this.$utils.getParams(this, "periods"),
                  "lottery",
                  this.shareTaskId
                );
              }
            }
          })
          .catch(() => {
            _this.isShareClick = false;
            _this.$commonJS.toastI("图片生成失败，请重试");
          });
      }
    },
    sendSaHtmd(type) {
      // 自定义埋点
      var elementContent = "";
      if (type == "shareFriend") {
        elementContent = "微信好友";
      } else if (type == "shareWX") {
        elementContent = "微信朋友圈";
      } else if (type == "save") {
        elementContent = "保存到相冊";
      }
      sensors.track("app_click", {
        title: this.dataConfig.titleName ? this.dataConfig.titleName : "",
        url: window.location.href,
        element_content: elementContent,
      });
    },
    wxShareSend: function (type, base64Src) {
      var shareObj = {
        type: type,
        imgFile: base64Src, // 图片base64
      };
      if (this.isAndroid) {
        window.jsObj &&
          window.jsObj.requireAsync(
            "wxShareSave",
            "",
            JSON.stringify(shareObj)
          );
      } else if (this.isIOS) {
        window.webkit &&
          window.webkit.messageHandlers &&
          window.webkit.messageHandlers.requireAsync.postMessage([
            "wxShareSave",
            "",
            JSON.stringify(shareObj),
          ]);
      }
    },
    getShareResult(data) {
      // 隐藏弹框并小黑条提示
      if (data.isShare) {
        this.$emit("shareDialog", false);
        this.isShareClick = false;
        data.type == "save" && this.$commonJS.toastI("保存成功");
      } else {
        this.$commonJS.toastI("图片生成失败，请重试");
        this.isShareClick = false;
      }
    },
  },
};
</script>
<style lang="scss">
.isShareImg {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  min-height: 100%;
  min-width: 100%;
  background: rgba(0, 0, 0, 0.65);
  z-index: 9;

  .shareImgContainer {
    position: absolute;
    // height: 8.8rem;
    width: 100%;
    bottom: 3.42rem;
    left: 50%;
    transform: translateX(-50%);
    z-index: 99999;

    .shareCon {
      display: flex;
      justify-content: center;
    }
  }

  .isVisibleShare {
    margin: 0 auto;

    .shareContent {
      width: 100%;
      background: #ffffff;
      border-radius: 0.28rem 0.28rem 0 0;
      position: absolute;
      bottom: 0;
      left: 0;

      .shareDetail {
        display: flex;
        padding: 1.4rem 0 0.6rem 0;
        width: 100%;
        justify-content: space-evenly;

        .shareItem {
          // flex: 1;
          display: flex;

          .itemCenter {
            display: flex;
            flex-direction: column;
            align-items: center;

            .shareItemImg {
              width: 1rem;
              height: 1rem;

              img {
                width: 1rem;
                height: 1rem;
              }
            }

            .shareItemText {
              margin-top: 0.2rem;
              font-size: 0.22rem;
              font-family: PingFangSC, PingFangSC-Regular;
              color: #999999;
              line-height: 0.22rem;
            }
          }
        }
      }
    }
  }

  .shareCanel {
    width: 100%;
    background: #f5f7fc;
    text-align: center;
    font-size: 0.36rem;
    font-family: PingFangSC, PingFangSC-Regular;
    padding: 0.3rem 0;
    color: #333333;
  }

  .shareImgPlaceholder {
    width: 100%;
    position: absolute;
    top: 2.1rem;

    .shareImgRefresh {
      margin-top: 1.34rem !important;
    }

    .shareImgLoading {
      width: 100%;
      text-align: center;
      font-size: 0.3rem;
      color: rgba(255, 255, 255, 0.7);
      margin-top: 0.2rem;
    }

    .shareImgLoadingbtn {
      width: 1.72rem;
      height: 0.48rem;
      border: 0.01rem solid #ffffff;
      border-radius: 0.3rem;
      margin: 0 auto;
      margin-top: 0.4rem;
      font-size: 0.28rem;
      color: #ffffff;
      text-align: center;
      line-height: 0.48rem;
    }

    .loading {
      width: 3rem;
      opacity: 0.8;
      display: block;
      margin: 0 auto;
      margin-top: 0.3rem;
    }

    .reload {
      width: 2rem;
      display: block;
      margin: 0 auto;
    }
  }

  .mint-swipe-item {
    text-align: center;
  }

  .shareImgBg {
    width: 4.5rem;
    border-radius: 0.2rem;
    position: relative;
    color: rgba(0, 111, 152, 1);
    margin: 0.2rem;

    & > img {
      width: 4.5rem;
      height: 6.86rem;
      background: #ffffff;
      border-radius: 0.2rem 0.2rem 0 0;
    }

    .linkCodeContent {
      width: 100%;
      padding: 0.24rem 0.31rem;
      background: #fff;
      border-radius: 0 0 0.14rem 0.14rem;
      box-shadow: 0px 0.02rem 0.2rem 0px rgba(0, 0, 0, 0.25);
      display: flex;

      .linkCode {
        width: 0.84rem;
        height: 0.84rem;
        border-radius: 0.03rem;
        display: flex;
        justify-content: center;
        align-items: center;

        img {
          width: 0.84rem;
          height: 0.84rem;
        }
      }

      .linkCodeText {
        flex: 1;
        margin-left: 0.2rem;
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;

        .linkCodeTitle {
          font-size: 0.26rem;
          font-family: SourceHanSansCN, SourceHanSansCN-Medium;
          font-weight: bold;
          color: #333333;
        }

        .linkCodeSubTitle {
          margin-top: 0.14rem;
          font-size: 0.19rem;
          font-family: SourceHanSansCN, SourceHanSansCN-Regular;
          color: #666666;
        }
      }
    }
  }

  .answerCard {
    width: 4.5rem;
    position: relative;

    .recommendBg {
      width: 4.5rem;
      border-radius: 0.14rem 0.14rem 0 0;
    }

    .cardContent {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      bottom: 1.05rem;
      width: calc(100% - 0.28rem);
      background: transparent;
      border: 0.01rem solid #999999;
      border-radius: 0.14rem;
      padding: 0 0.14rem;
      overflow: hidden;

      .cardTop {
        margin: 0.64rem 0 0.21rem;

        .cornerLabel {
          position: absolute;
          top: -0.01rem;
          left: -0.01rem;
          height: 0.43rem;
          line-height: 0.43rem;
          transform: translate(-0.18rem, 0);

          .mainTitle {
            transform: translate(0.18rem, 0);
            display: inline-block;
            background: linear-gradient(180deg, #f9bc5f, #fe3955);
            font-size: 0.2rem;
            font-family: PingFangSC, PingFangSC-Regular;
            color: #ffffff;
            border-radius: 0 0 0.14rem 0;
            vertical-align: top;
            z-index: 9999;

            span {
              margin: 0 0.14rem;
            }
          }

          .subTitle {
            display: inline-block;
            background: #ffc99f;
            border-radius: 0 0 0.14rem 0;
            font-size: 0.26rem;
            font-family: PingFangSC, PingFangSC-Medium;
            font-weight: 500;
            color: #660000;
            z-index: 999;

            span {
              margin: 0 0.18rem 0 0.32rem;
            }
          }
        }

        .fundManagerInfo {
          display: flex;

          .managerHead {
            width: 1.29rem;
            height: 1.29rem;
            padding: 0.02rem;

            .headmg {
              width: 100%;
              height: 100%;

              img {
                width: 1.29rem;
                height: 1.29rem;
              }
            }
          }

          .managerInfo {
            margin-left: 0.12rem;

            .marketTalk {
              transform: scale(1);
              letter-spacing: 0.002rem;
              text-align: left;
              font-size: 0.16rem;
              color: #333333;
            }

            .marketLabels {
              margin-top: 0.15rem;

              .labelItem {
                display: inline-block;
                border: 0.015rem solid #cccccc;
                border-radius: 0.06rem;
                margin: 0 0.07rem 0.07rem 0;
                align-items: center;

                .labelItemText {
                  transform: translate(-50%, -100%);
                  display: inline-block;
                  transform: scale(0.8);
                  font-size: 0.16rem;
                  font-family: PingFangSC, PingFangSC-Regular;
                  color: #666666;
                }
              }
            }
          }
        }
      }

      .cardBottom {
        padding: 0.36rem 0 0.21rem;
        border-top: 0.02rem dashed #999999;
        position: relative;

        .cornerLabel2 {
          display: flex;
          position: absolute;
          top: 0;
          left: 0;

          img {
            width: 0.83rem;
            height: 0.29rem;
          }
        }

        .fundInfo {
          display: flex;
          position: relative;

          .fundInfoLeft {
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .fundInfoValue {
              font-size: 0.27rem;
              font-family: PingFangSC, PingFangSC-Medium;
              font-weight: 500;
              color: #fd4a56;
              line-height: 0.38rem;
            }

            .red {
              color: #fd4a56;
            }

            .green {
              color: #0cb849;
            }

            .fundInfoName {
              width: 1.5rem;
              font-size: 0.16rem;
              font-family: PingFangSC, PingFangSC-Regular;
              color: #666666;
              line-height: 0.22rem;
            }
          }

          .fundInfoRight {
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .fundInfoTitle {
              font-size: 0.21rem;
              font-family: PingFangSC, PingFangSC-Medium;
              font-weight: bold;
              color: #000000;
              line-height: 0.3rem;
              text-align: left;
              overflow: hidden;
            }

            .fundInfoSubTitle {
              font-size: 0.16rem;
              font-family: PingFangSC, PingFangSC-Regular;
              color: #666666;
              line-height: 0.22rem;
              text-align: left;
              overflow: hidden;
            }
          }
        }
      }
    }
  }

  .answerCardLinkCodeContent {
    width: 100%;
    padding: 0.24rem 0.31rem;
    background: #fff;
    border-radius: 0 0 0.14rem 0.14rem;
    box-shadow: 0px 0.02rem 0.2rem 0px rgba(0, 0, 0, 0.25);
    display: flex;
    margin-top: -0.02rem;

    .answerCardLinkCode {
      width: 0.84rem;
      height: 0.84rem;

      img {
        width: 0.84rem;
        height: 0.84rem;
      }
    }

    .answerCardLinkCodeText {
      margin-left: 0.2rem;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;

      .answerCardLinkCodeTitle {
        font-size: 0.26rem;
        font-family: SourceHanSansCN, SourceHanSansCN-Medium;
        font-weight: bold;
        color: #333333;
      }

      .answerCardLinkCodeSubTitle {
        margin-top: 0.14rem;
        font-size: 0.19rem;
        font-family: SourceHanSansCN, SourceHanSansCN-Regular;
        color: #666666;
      }
    }
  }
}

@supports (bottom: env(safe-area-inset-bottom)) {
  .shareContent {
    .shareCanel {
      padding: 0.3rem 0 calc(0.3rem + env(safe-area-inset-bottom)) 0;
    }
  }

  .isShareImg > .shareImgContainer {
    bottom: calc(3.42rem + env(safe-area-inset-bottom));
  }
}
</style>
<style>
.swiper-pagination {
  height: 0.06rem;
  bottom: 0.25rem !important;
}

.swiper-pagination-bullet-active {
  width: 0.24rem !important;
  height: 0.06rem;
  opacity: 1;
  background: #2351ba !important;
  border-radius: 0.06rem;
  box-shadow: 0px 0.01rem 0.01rem 0px rgba(6, 37, 107, 0.35) !important;
}

.swiper-pagination-bullet {
  width: 0.06rem;
  height: 0.06rem;
  opacity: 1;
  background: #b7c2e2;
  border-radius: 0.06rem;
}
</style>